<?php
/**
 * Auther: Joshua Conero
 * Date: 2018/5/2 0002 14:12
 * Email: brximl@163.com
 * Name: 事务甲乙服务类
 */

namespace app\common;


use hyang\Util;
use phpseclib\Crypt\AES;
use phpseclib\Crypt\Random;

class SvFaffair
{
    /**
     * 获取命令程序
     * @param string $cmd 密令
     * @param string|null $id 数据主键
     * @return array
     */
    static function getCmd($cmd, $id=null){
        $aes = new AES();
        $mkKey = false;
        $key = null;
        if($id){
            $key = db()
                ->table('fnc0020c')
                ->where(['listid'=>$id])
                ->value('cmd_key')
                ;
            if($key) $mkKey = true;
        }
        $key = $key? $key : sha1(Random::string(5). time());
        $aes->setKey($key);
        $cmd = base64_encode($aes->encrypt($cmd));
        $data = [
            'command' => $cmd
        ];
        if(!$mkKey){
            $data['cmd_key'] = $key;
        }
        return $data;
    }

    /**
     * 获取原始口令
     * @param $listid
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    static function getRaw($listid){
        $data = db()->table('fnc0020c')
            ->where(['listid' => $listid])
            ->find()
        ;
        $raw = null;
        if(isset($data['command']) && !empty($data['command'])){
            $cmd = $data['command'];
            $aes = new AES();
            $aes->setKey($data['cmd_key']);
            $raw = $aes->decrypt(base64_decode($cmd));
        }
        $data = Util::clearArrKey($data, ['cmd_key', 'command']);
        $data['raw'] = $raw;
        return $data;
    }
}